package plugins

import (
	"bufio"
	"crypto/tls"
	"fmt"
	"io"
	"ip-parser/internal/logger"
	"net"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

// IPInfo 存储IP信息
type IPInfo struct {
	Address    string // IP地址
	Source     string // 发现来源
	Confidence int    // 可信度（0-100）
}

// NetworkReconPlugin 网络侦察插件，整合了IP解析和CDN绕过功能
type NetworkReconPlugin struct {
	logger *logger.Logger
	// 存储最近的解析结果
	lastResult map[string]interface{}
}

// NewNetworkReconPlugin 创建新的网络侦察插件
func NewNetworkReconPlugin() *NetworkReconPlugin {
	return &NetworkReconPlugin{
		logger:     logger.NewLogger(),
		lastResult: make(map[string]interface{}),
	}
}

// GetDescription 获取插件描述
func (p *NetworkReconPlugin) GetDescription() string {
	return "全面的网络侦察工具：IP解析、CDN检测与绕过、端口扫描、服务识别"
}

// GetRequiredParams 获取插件所需参数
func (p *NetworkReconPlugin) GetRequiredParams() []PluginParamInfo {
	return []PluginParamInfo{
		{
			Name:        "target",
			Description: "目标域名或URL",
			Required:    true,
			Default:     "",
		},
		{
			Name:        "mode",
			Description: "工作模式: basic(基础), cdn_bypass(CDN绕过), full(全面扫描)",
			Required:    false,
			Default:     "basic",
		},
		{
			Name:        "port_range",
			Description: "端口扫描范围，例如: 1-1024, 80,443,8080",
			Required:    false,
			Default:     "1-1024",
		},
		{
			Name:        "concurrency",
			Description: "并发扫描线程数",
			Required:    false,
			Default:     "30",
		},
		{
			Name:        "timeout",
			Description: "请求超时时间（秒）",
			Required:    false,
			Default:     "5",
		},
		{
			Name:        "scan_depth",
			Description: "扫描深度（1-4，越大越深入）",
			Required:    false,
			Default:     "2",
		},
		{
			Name:        "wordlist",
			Description: "自定义子域名字典路径",
			Required:    false,
			Default:     "",
		},
	}
}

// Execute 执行网络侦察
func (p *NetworkReconPlugin) Execute(args map[string]interface{}) error {
	// 获取目标
	target, ok := args["target"].(string)
	if !ok {
		return fmt.Errorf("缺少必要参数: target (域名或URL)")
	}

	// 获取工作模式
	mode := "basic" // 默认为基础模式
	if m, ok := args["mode"].(string); ok {
		mode = m
	}

	// 获取端口扫描范围
	portRange := "1-1024" // 默认端口范围
	if pr, ok := args["port_range"].(string); ok {
		portRange = pr
	}

	// 获取超时设置
	timeout := 5 // 默认超时5秒
	if t, ok := args["timeout"].(int); ok {
		timeout = t
	} else if tStr, ok := args["timeout"].(string); ok {
		// 尝试从字符串转换
		if tVal, err := strconv.Atoi(tStr); err == nil {
			timeout = tVal
		}
	}

	// 获取并发数
	concurrency := 30 // 默认并发数
	if c, ok := args["concurrency"].(int); ok {
		concurrency = c
	} else if cStr, ok := args["concurrency"].(string); ok {
		// 尝试从字符串转换
		if cVal, err := strconv.Atoi(cStr); err == nil {
			concurrency = cVal
		}
	}

	// 获取扫描深度
	scanDepth := 2 // 默认深度
	if d, ok := args["scan_depth"].(int); ok {
		scanDepth = d
	} else if dStr, ok := args["scan_depth"].(string); ok {
		fmt.Sscanf(dStr, "%d", &scanDepth)
	}

	// 获取字典路径
	wordlist := "" // 默认使用内置字典
	if w, ok := args["wordlist"].(string); ok {
		wordlist = w
	}

	// 将配置保存到lastResult中
	p.lastResult["target"] = target
	p.lastResult["concurrency"] = concurrency
	p.lastResult["timeout"] = timeout
	p.lastResult["scan_depth"] = scanDepth

	p.logger.Separator()
	p.logger.Info("开始网络侦察任务")
	p.logger.Info("目标: %s", target)
	p.logger.Info("工作模式: %s", mode)
	p.logger.Info("端口范围: %s", portRange)
	p.logger.Info("超时设置: %d秒", timeout)
	p.logger.Info("并发数: %d", concurrency)
	p.logger.Info("扫描深度: %d", scanDepth)

	// 根据不同模式执行不同扫描策略
	switch strings.ToLower(mode) {
	case "basic":
		return p.basicRecon(target, portRange, timeout, concurrency)
	case "cdn_bypass":
		return p.cdnBypassRecon(target, portRange, timeout, concurrency, scanDepth, wordlist)
	case "full":
		return p.fullRecon(target, portRange, timeout, concurrency, scanDepth, wordlist)
	default:
		return fmt.Errorf("不支持的工作模式: %s", mode)
	}
}

// GetLastResult 获取最近的解析结果
func (p *NetworkReconPlugin) GetLastResult() map[string]interface{} {
	return p.lastResult
}

// basicRecon 执行基础侦察，包括IP解析、端口扫描和CDN检测
func (p *NetworkReconPlugin) basicRecon(target, portRange string, timeoutSeconds, concurrency int) error {
	// 1. 解析IP地址
	p.logger.Info("正在解析IP地址...")
	ips, err := p.resolveIP(target)
	if err != nil {
		return fmt.Errorf("IP解析失败: %v", err)
	}

	// 显示解析结果
	var ipRows [][]string
	for _, ip := range ips {
		ipRows = append(ipRows, []string{ip})
	}
	p.logger.Table(
		[]string{"IP地址"},
		ipRows,
	)

	// 保存解析结果
	p.lastResult["ips"] = ips
	if len(ips) > 0 {
		p.lastResult["primary_ip"] = ips[0]
	}

	// 2. 扫描端口
	if len(ips) > 0 {
		primaryIP := ips[0]
		p.logger.Info("使用主要IP地址进行端口扫描: %s", primaryIP)

		// 解析端口范围
		ports, err := p.parsePortRange(portRange)
		if err != nil {
			return fmt.Errorf("端口范围解析失败: %v", err)
		}

		p.logger.Info("开始扫描 %d 个端口...", len(ports))
		openPorts, services, err := p.scanPorts(primaryIP, ports, timeoutSeconds, concurrency)
		if err != nil {
			return fmt.Errorf("端口扫描失败: %v", err)
		}

		// 显示开放端口
		if len(openPorts) > 0 {
			var portRows [][]string
			for i, port := range openPorts {
				portRows = append(portRows, []string{
					fmt.Sprintf("%d", port),
					services[i],
				})
			}
			p.logger.Table(
				[]string{"端口", "服务"},
				portRows,
			)

			// 保存端口扫描结果
			p.lastResult["open_ports"] = openPorts
			p.lastResult["services"] = services
		} else {
			p.logger.Warning("未发现开放端口")
		}

		// 3. 检测CDN和代理信息
		p.logger.Info("检测CDN和代理信息...")
		cdnInfo, err := p.detectCDN(target)
		if err == nil && cdnInfo != "" {
			p.logger.Warning("目标可能使用CDN或代理: %s", cdnInfo)
			p.lastResult["cdn_info"] = cdnInfo
		} else {
			p.logger.Success("未检测到CDN或代理")
		}
	}

	p.logger.Success("基础网络侦察任务完成")
	p.logger.Separator()
	return nil
}

// resolveIP 解析IP地址
func (p *NetworkReconPlugin) resolveIP(target string) ([]string, error) {
	var domain string

	// 检查输入是否为URL
	if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") {
		// 解析URL获取域名
		parsedURL, err := url.Parse(target)
		if err != nil {
			return nil, fmt.Errorf("URL解析失败: %v", err)
		}
		domain = parsedURL.Hostname()
		p.logger.Info("从URL提取域名: %s", domain)
	} else {
		// 输入已经是域名或IP
		domain = target
	}

	// 检查是否已经是IP地址
	if net.ParseIP(domain) != nil {
		p.logger.Info("输入已经是IP地址")
		return []string{domain}, nil
	}

	// 尝试DNS解析
	p.logger.Info("尝试DNS解析: %s", domain)
	ips, err := net.LookupIP(domain)
	if err != nil {
		return nil, fmt.Errorf("DNS解析失败: %v", err)
	}

	// 提取IPv4地址
	var ipList []string
	for _, ip := range ips {
		if ipv4 := ip.To4(); ipv4 != nil {
			ipList = append(ipList, ipv4.String())
		}
	}

	if len(ipList) == 0 {
		return nil, fmt.Errorf("未找到IPv4地址")
	}

	return ipList, nil
}

// parsePortRange 解析端口范围字符串
func (p *NetworkReconPlugin) parsePortRange(portRange string) ([]int, error) {
	var ports []int
	ranges := strings.Split(portRange, ",")

	for _, r := range ranges {
		r = strings.TrimSpace(r)
		if r == "" {
			continue
		}

		parts := strings.Split(r, "-")
		if len(parts) == 1 {
			// 单个端口
			port, err := strconv.Atoi(parts[0])
			if err != nil {
				return nil, fmt.Errorf("无效的端口: %s", parts[0])
			}
			if port < 1 || port > 65535 {
				return nil, fmt.Errorf("端口范围无效: %d", port)
			}
			ports = append(ports, port)
		} else if len(parts) == 2 {
			// 端口范围
			start, err := strconv.Atoi(parts[0])
			if err != nil {
				return nil, fmt.Errorf("无效的起始端口: %s", parts[0])
			}
			end, err := strconv.Atoi(parts[1])
			if err != nil {
				return nil, fmt.Errorf("无效的结束端口: %s", parts[1])
			}
			if start < 1 || start > 65535 || end < 1 || end > 65535 || start > end {
				return nil, fmt.Errorf("端口范围无效: %d-%d", start, end)
			}
			for port := start; port <= end; port++ {
				ports = append(ports, port)
			}
		} else {
			return nil, fmt.Errorf("无效的端口范围格式: %s", r)
		}
	}

	// 去重
	uniquePorts := make([]int, 0, len(ports))
	seen := make(map[int]bool)
	for _, port := range ports {
		if !seen[port] {
			seen[port] = true
			uniquePorts = append(uniquePorts, port)
		}
	}

	// 排序
	sort.Ints(uniquePorts)
	return uniquePorts, nil
}

// scanPorts 扫描端口
func (p *NetworkReconPlugin) scanPorts(ip string, ports []int, timeoutSeconds, concurrency int) ([]int, []string, error) {
	var openPorts []int
	var services []string
	var mutex sync.Mutex // 添加互斥锁保护并发写入

	timeout := time.Duration(timeoutSeconds) * time.Second
	total := len(ports)

	// 设置实际并发数，不超过端口数量
	actualConcurrency := concurrency
	if len(ports) < concurrency {
		actualConcurrency = len(ports)
	}

	// 创建通道用于任务分发和结果收集
	jobs := make(chan int, total)
	results := make(chan int, total)

	// 启动工作协程
	var wg sync.WaitGroup
	for i := 0; i < actualConcurrency; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for port := range jobs {
				addr := fmt.Sprintf("%s:%d", ip, port)
				conn, err := net.DialTimeout("tcp", addr, timeout)
				if err == nil {
					results <- port
					conn.Close()
				} else {
					results <- -1 // 表示端口未开放
				}
			}
		}()
	}

	// 分发任务
	for _, port := range ports {
		jobs <- port
	}
	close(jobs)

	// 创建进度更新协程
	go func() {
		for i := 1; i <= total; i++ {
			p.logger.Progress(i, total, "端口扫描")
			port := <-results
			if port != -1 { // 端口开放
				mutex.Lock()
				openPorts = append(openPorts, port)
				services = append(services, GetServiceName(port))
				mutex.Unlock()
			}
		}
	}()

	// 等待所有工作完成
	wg.Wait()

	// 按端口顺序排序结果
	sort.Slice(openPorts, func(i, j int) bool {
		return openPorts[i] < openPorts[j]
	})

	// 重新获取服务名称以匹配排序后的端口
	services = make([]string, len(openPorts))
	for i, port := range openPorts {
		services[i] = GetServiceName(port)
	}

	return openPorts, services, nil
}

// detectCDN 检测目标是否使用CDN
func (p *NetworkReconPlugin) detectCDN(target string) (string, error) {
	// CDN提供商CNAME标记列表
	cdnCNAMEs := map[string]string{
		"akamai":        "akamai.net",
		"cloudflare":    "cloudflare",
		"cloudfront":    "cloudfront.net",
		"fastly":        "fastly",
		"incapsula":     "incapsula",
		"cdnjs":         "cdnjs",
		"cdn77":         "cdn77",
		"maxcdn":        "maxcdn",
		"belugacdn":     "belugacdn",
		"cachefly":      "cachefly",
		"edgecast":      "edgecast",
		"limolabs":      "limocdn",
		"sucuri":        "sucuri",
		"chinacache":    "chinacache",
		"limelight":     "llnwd.net",
		"cdn.net":       "cdn.net",
		"google cloud":  "googleusercontent",
		"oracle cloud":  "oraclecloud",
		"airee":         "airee",
		"azure":         "azureedge.net",
		"azion":         "azioncdn.net",
		"cdnetworks":    "cdnetworks",
		"cdnify":        "cdnify",
		"cdnsun":        "cdnsun.net",
		"stackpath":     "stackpathdns.com",
		"ddos-guard":    "ddos-guard",
		"dosarrest":     "dosarrest",
		"medianova":     "mncdn.com",
		"netlify":       "netlify.com",
		"wscloudcdn":    "wscloudcdn.com",
		"quantil":       "quantil.com",
		"imperva":       "imperva",
		"alicdn":        "alicdn.com",
		"aliyun":        "aliyuncs.com",
		"qiniu":         "qiniudns.com",
		"tencent cloud": "qcloud.com",
		"yunjiasu":      "yunjiasu",
		"vercel":        "vercel-dns.com",
	}

	var domain string
	// 检查输入是否为URL
	if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") {
		// 解析URL获取域名
		parsedURL, err := url.Parse(target)
		if err != nil {
			return "", fmt.Errorf("URL解析失败: %v", err)
		}
		domain = parsedURL.Hostname()
	} else {
		// 输入已经是域名或IP
		domain = target
	}

	// 检查是否已经是IP地址
	if net.ParseIP(domain) != nil {
		return "", nil // IP地址通常不使用CDN
	}

	// 检查CNAME记录
	cnames, err := net.LookupCNAME(domain)
	if err == nil {
		for provider, pattern := range cdnCNAMEs {
			if strings.Contains(cnames, pattern) {
				return provider, nil
			}
		}
	}

	// 检查HTTP响应头
	cdnHeaders := map[string]map[string]string{
		"cloudflare":       {"server": "cloudflare", "cf-ray": ""},
		"akamai":           {"x-akamai-transformed": "", "x-akamai-ssl-client-sid": ""},
		"cloudfront":       {"x-amz-cf-id": "", "x-amz-cf-pop": ""},
		"fastly":           {"fastly-debug-digest": "", "x-served-by": "cache"},
		"maxcdn":           {"x-cdn": "maxcdn"},
		"incapsula":        {"x-cdn": "incapsula", "x-iinfo": ""},
		"sucuri":           {"x-sucuri-id": "", "x-sucuri-cache": ""},
		"airee":            {"x-airee-node": "", "x-airee-cache": ""},
		"azure cdn":        {"x-msedge-ref": ""},
		"keycdn":           {"x-cdn": "keycdn"},
		"cdn77":            {"x-cdn": "cdn77"},
		"ddos-guard":       {"server": "ddos-guard"},
		"quantil":          {"x-quantil-node": "", "x-quantil-requestid": ""},
		"imperva":          {"x-iinfo": ""},
		"aliyun":           {"server": "tengine"},
		"tencent cloud":    {"server": "tencent"},
		"vercel":           {"x-vercel-cache": "", "x-vercel-id": ""},
		"jsdelivr":         {"x-served-by": "jsdelivr"},
		"stackpath":        {"x-served-by": "stackpath"},
		"beluga":           {"server": "beluga"},
		"edgio":            {"x-edgio": ""},
		"google cloud cdn": {"x-cloud-trace-context": ""},
	}

	client := &http.Client{
		Timeout: 5 * time.Second,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	url := target
	if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
		url = "https://" + url
	}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}

	// 添加常见浏览器User-Agent
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

	resp, err := client.Do(req)
	if err != nil {
		// 尝试HTTP
		if strings.HasPrefix(url, "https://") {
			url = strings.Replace(url, "https://", "http://", 1)
			req, err = http.NewRequest("GET", url, nil)
			if err != nil {
				return "", err
			}
			req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
			resp, err = client.Do(req)
			if err != nil {
				return "", err
			}
		} else {
			return "", err
		}
	}
	defer resp.Body.Close()

	// 检查响应头
	for provider, headers := range cdnHeaders {
		for header, value := range headers {
			if h := resp.Header.Get(header); h != "" {
				if value == "" || strings.Contains(strings.ToLower(h), value) {
					return provider, nil
				}
			}
		}
	}

	return "", nil
}

// cdnBypassRecon 执行CDN绕过侦察
func (p *NetworkReconPlugin) cdnBypassRecon(target, portRange string, timeout, concurrency, scanDepth int, wordlist string) error {
	p.logger.Info("[+] 初始化CDN绕过模块")
	p.logger.Info("[+] 目标: %s", target)

	// 存储所有检测到的IP
	var discoveredIPs []IPInfo
	var ipsMutex sync.Mutex

	// 1. 从历史DNS记录查找
	p.logger.Info("[+] 阶段1: 查询历史DNS记录")
	historicIPs, err := p.findHistoricIPs(target)
	if err != nil {
		p.logger.Error("[-] 历史DNS记录查询失败: %v", err)
	} else {
		p.logger.Success("[+] 从历史DNS记录发现 %d 个潜在IP", len(historicIPs))
		ipsMutex.Lock()
		discoveredIPs = append(discoveredIPs, historicIPs...)
		ipsMutex.Unlock()
	}

	// 2. 检查SSL证书
	p.logger.Info("[+] 阶段2: 分析SSL证书关联")
	sslIPs, err := p.checkSSLCertificates(target, timeout)
	if err != nil {
		p.logger.Error("[-] SSL证书分析失败: %v", err)
	} else {
		p.logger.Success("[+] 从SSL证书分析发现 %d 个潜在IP", len(sslIPs))
		ipsMutex.Lock()
		discoveredIPs = append(discoveredIPs, sslIPs...)
		ipsMutex.Unlock()
	}

	// 3. 子域名枚举
	if scanDepth >= 2 {
		p.logger.Info("[+] 阶段3: 子域名枚举")
		subdomains, err := p.enumerateSubdomains(target, concurrency, timeout, wordlist)
		if err != nil {
			p.logger.Error("[-] 子域名枚举失败: %v", err)
		} else {
			p.logger.Success("[+] 发现 %d 个子域名", len(subdomains))

			// 解析子域名对应的IP
			p.logger.Info("[+] 正在解析子域名IP...")
			subdomainIPs, err := p.resolveSubdomains(subdomains, concurrency, timeout)
			if err != nil {
				p.logger.Error("[-] 子域名IP解析失败: %v", err)
			} else {
				p.logger.Success("[+] 从子域名解析出 %d 个潜在IP", len(subdomainIPs))
				ipsMutex.Lock()
				discoveredIPs = append(discoveredIPs, subdomainIPs...)
				ipsMutex.Unlock()
			}
		}
	}

	// 4. 邮件服务器分析
	if scanDepth >= 2 {
		p.logger.Info("[+] 阶段4: 邮件服务器分析")
		mailIPs, err := p.analyzeMailServers(target, timeout)
		if err != nil {
			p.logger.Error("[-] 邮件服务器分析失败: %v", err)
		} else {
			p.logger.Success("[+] 从邮件服务器发现 %d 个潜在IP", len(mailIPs))
			ipsMutex.Lock()
			discoveredIPs = append(discoveredIPs, mailIPs...)
			ipsMutex.Unlock()
		}
	}

	// 5. 云服务提供商API查询
	if scanDepth >= 3 {
		p.logger.Info("[+] 阶段5: 云服务商关联分析")
		cloudIPs, err := p.checkCloudProviders(target, timeout)
		if err != nil {
			p.logger.Error("[-] 云服务商分析失败: %v", err)
		} else {
			p.logger.Success("[+] 从云服务关联发现 %d 个潜在IP", len(cloudIPs))
			ipsMutex.Lock()
			discoveredIPs = append(discoveredIPs, cloudIPs...)
			ipsMutex.Unlock()
		}
	}

	// 6. 内容验证和排序
	p.logger.Info("[+] 阶段6: 内容验证和相似度排名")
	if len(discoveredIPs) > 0 {
		// 按可信度排序
		p.sortIPsByConfidence(discoveredIPs)

		// 获取目标网站指纹
		var targetFingerprint string
		url := target
		if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
			url = "https://" + url
		}
		targetFingerprint, _ = p.getWebsiteFingerprint(url, timeout)

		// 显示结果
		var ipRows [][]string
		for i, ip := range discoveredIPs {
			// 只显示排名前20的IP
			if i >= 20 {
				break
			}

			// 计算与原站的相似度
			similarityScore := 0.0
			if targetFingerprint != "" {
				ipURL := fmt.Sprintf("http://%s", ip.Address)
				ipFingerprint, _ := p.getWebsiteFingerprint(ipURL, timeout)
				if ipFingerprint != "" {
					similarityScore = p.calculateSimilarity(targetFingerprint, ipFingerprint)
				}
			}

			similarityStr := "-"
			if similarityScore > 0 {
				similarityStr = fmt.Sprintf("%.1f%%", similarityScore*100)
			}

			ipRows = append(ipRows, []string{
				ip.Address,
				ip.Source,
				fmt.Sprintf("%d%%", ip.Confidence),
				similarityStr,
			})
		}

		p.logger.Table(
			[]string{"IP地址", "来源", "可信度", "相似度"},
			ipRows,
		)

		// 保存结果
		p.lastResult["discovered_ips"] = discoveredIPs
		if len(discoveredIPs) > 0 {
			p.lastResult["real_ip"] = discoveredIPs[0].Address
		}

		// 对发现的最可能的真实IP进行端口扫描
		if len(discoveredIPs) > 0 {
			realIP := discoveredIPs[0].Address
			p.logger.Info("[+] 对最可能的真实IP进行端口扫描: %s", realIP)

			// 解析端口范围
			ports, err := p.parsePortRange(portRange)
			if err != nil {
				return fmt.Errorf("端口范围解析失败: %v", err)
			}

			p.logger.Info("[+] 开始扫描 %d 个端口...", len(ports))
			openPorts, services, err := p.scanPorts(realIP, ports, timeout, concurrency)
			if err != nil {
				return fmt.Errorf("端口扫描失败: %v", err)
			}

			// 显示开放端口
			if len(openPorts) > 0 {
				var portRows [][]string
				for i, port := range openPorts {
					portRows = append(portRows, []string{
						fmt.Sprintf("%d", port),
						services[i],
					})
				}
				p.logger.Table(
					[]string{"端口", "服务"},
					portRows,
				)

				// 保存端口扫描结果
				p.lastResult["open_ports"] = openPorts
				p.lastResult["services"] = services
			} else {
				p.logger.Warning("未发现开放端口")
			}
		}
	} else {
		p.logger.Warning("未能发现任何绕过CDN的可能IP")
	}

	p.logger.Success("CDN绕过侦察任务完成")
	p.logger.Separator()
	return nil
}

// fullRecon 执行完整侦察，包括基础侦察和CDN绕过
func (p *NetworkReconPlugin) fullRecon(target, portRange string, timeout, concurrency, scanDepth int, wordlist string) error {
	// 先执行基础侦察
	err := p.basicRecon(target, portRange, timeout, concurrency)
	if err != nil {
		return err
	}

	// 检查是否检测到CDN
	cdnInfo, ok := p.lastResult["cdn_info"].(string)
	if ok && cdnInfo != "" {
		p.logger.Info("检测到CDN: %s，尝试绕过...", cdnInfo)
		// 执行CDN绕过侦察
		return p.cdnBypassRecon(target, portRange, timeout, concurrency, scanDepth, wordlist)
	}

	p.logger.Success("完整网络侦察任务完成")
	return nil
}

// findHistoricIPs 查找历史DNS记录
func (p *NetworkReconPlugin) findHistoricIPs(domain string) ([]IPInfo, error) {
	var results []IPInfo

	// 模拟查询多个DNS历史记录服务
	p.logger.Info("尝试查询DNS历史记录服务...")

	// 这里仅模拟行为，实际API调用需要适当的API密钥或解析HTML
	// 在真实环境中，应该使用各服务的API或解析HTML响应

	// 添加一些常见的IP段来模拟历史DNS记录
	// 在实际项目中应该从API响应中解析真实数据
	simulated := []struct {
		ip         string
		source     string
		confidence int
	}{
		{"8.8.8.8", "DNS历史记录", 40},
		{"1.1.1.1", "DNS历史记录", 35},
	}

	for _, item := range simulated {
		results = append(results, IPInfo{
			Address:    item.ip,
			Source:     item.source,
			Confidence: item.confidence,
		})
	}

	return results, nil
}

// checkSSLCertificates 分析SSL证书关联查找真实IP
func (p *NetworkReconPlugin) checkSSLCertificates(domain string, timeout int) ([]IPInfo, error) {
	var results []IPInfo

	// 创建TLS配置，禁用证书验证
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
	}

	// 尝试获取SSL证书
	dialer := &net.Dialer{
		Timeout: time.Duration(timeout) * time.Second,
	}

	p.logger.Info("尝试获取SSL证书信息...")

	conn, err := tls.DialWithDialer(dialer, "tcp", domain+":443", tlsConfig)
	if err != nil {
		return nil, fmt.Errorf("连接失败: %v", err)
	}
	defer conn.Close()

	// 获取证书链
	certs := conn.ConnectionState().PeerCertificates
	if len(certs) == 0 {
		return nil, fmt.Errorf("未找到证书")
	}

	// 分析证书中的SAN (Subject Alternative Name)
	for _, cert := range certs {
		for _, san := range cert.DNSNames {
			if san != domain && !strings.HasPrefix(san, "*.") {
				// 解析关联域名
				ips, err := net.LookupIP(san)
				if err == nil {
					for _, ip := range ips {
						if ipv4 := ip.To4(); ipv4 != nil {
							p.logger.Info("从证书SAN找到域名: %s -> IP: %s", san, ipv4.String())
							results = append(results, IPInfo{
								Address:    ipv4.String(),
								Source:     "SSL证书 - " + san,
								Confidence: 60,
							})
						}
					}
				}
			}
		}
	}

	// 检查证书颁发机构，可能揭示托管信息
	for _, cert := range certs {
		issuer := cert.Issuer.String()
		if strings.Contains(issuer, "Amazon") || strings.Contains(issuer, "AWS") {
			p.logger.Info("证书颁发机构显示可能托管在AWS")
		} else if strings.Contains(issuer, "Google") {
			p.logger.Info("证书颁发机构显示可能托管在Google Cloud")
		} else if strings.Contains(issuer, "Microsoft") || strings.Contains(issuer, "Azure") {
			p.logger.Info("证书颁发机构显示可能托管在Azure")
		}
	}

	return results, nil
}

// enumerateSubdomains 枚举子域名
func (p *NetworkReconPlugin) enumerateSubdomains(domain string, concurrency, timeout int, wordlist string) ([]string, error) {
	var subdomains []string
	var subdomainsMutex sync.Mutex

	// 准备常见子域名列表
	var words []string
	if wordlist != "" {
		// 从文件读取自定义字典
		file, err := os.Open(wordlist)
		if err != nil {
			return nil, fmt.Errorf("无法打开字典文件: %v", err)
		}
		defer file.Close()

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			word := strings.TrimSpace(scanner.Text())
			if word != "" && !strings.HasPrefix(word, "#") {
				words = append(words, word)
			}
		}

		if err := scanner.Err(); err != nil {
			return nil, fmt.Errorf("读取字典文件失败: %v", err)
		}
	} else {
		// 使用内置常见子域名列表
		words = []string{
			"www", "mail", "remote", "blog", "webmail", "server", "ns1", "ns2", "smtp", "secure",
			"vpn", "m", "shop", "ftp", "api", "api2", "admin", "dev", "test", "portal", "beta",
			"auth", "gateway", "staff", "cms", "stage", "static", "media", "intranet", "cloud",
			"cdn", "cdn2", "downloads", "img", "images", "app", "apps", "assets", "docs", "info",
		}
	}

	p.logger.Info("使用 %d 个词汇进行子域名枚举...", len(words))

	// 创建工作协程池
	var wg sync.WaitGroup
	jobCh := make(chan string, len(words))

	// 启动工作协程
	for i := 0; i < concurrency; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			for word := range jobCh {
				subdomain := word + "." + domain
				_, err := net.LookupHost(subdomain)
				if err == nil {
					subdomainsMutex.Lock()
					subdomains = append(subdomains, subdomain)
					subdomainsMutex.Unlock()
					p.logger.Info("发现子域名: %s", subdomain)
				}
			}
		}()
	}

	// 分发任务
	for _, word := range words {
		jobCh <- word
	}
	close(jobCh)

	// 等待所有任务完成
	wg.Wait()

	return subdomains, nil
}

// resolveSubdomains 解析子域名IP
func (p *NetworkReconPlugin) resolveSubdomains(subdomains []string, concurrency, timeout int) ([]IPInfo, error) {
	var results []IPInfo
	var resultsMutex sync.Mutex

	// 创建工作协程池
	var wg sync.WaitGroup
	jobCh := make(chan string, len(subdomains))

	// 启动工作协程
	for i := 0; i < concurrency; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			for subdomain := range jobCh {
				ips, err := net.LookupIP(subdomain)
				if err == nil {
					for _, ip := range ips {
						if ipv4 := ip.To4(); ipv4 != nil {
							// 检查是否是CDN IP
							if !p.isCDNIP(ipv4.String()) {
								resultsMutex.Lock()
								results = append(results, IPInfo{
									Address:    ipv4.String(),
									Source:     "子域名 - " + subdomain,
									Confidence: 70,
								})
								resultsMutex.Unlock()
							}
						}
					}
				}
			}
		}()
	}

	// 分发任务
	for _, subdomain := range subdomains {
		jobCh <- subdomain
	}
	close(jobCh)

	// 等待所有任务完成
	wg.Wait()

	return results, nil
}

// isCDNIP 检查IP是否属于已知CDN
func (p *NetworkReconPlugin) isCDNIP(ip string) bool {
	// 检查常见CDN IP范围
	cdnRanges := map[string][]string{
		"Cloudflare": {
			"103.21.244.0/22",
			"103.22.200.0/22",
			"103.31.4.0/22",
			"104.16.0.0/12",
			"108.162.192.0/18",
			"131.0.72.0/22",
			"141.101.64.0/18",
			"162.158.0.0/15",
			"172.64.0.0/13",
			"173.245.48.0/20",
			"188.114.96.0/20",
			"190.93.240.0/20",
			"197.234.240.0/22",
			"198.41.128.0/17",
		},
		"Akamai": {
			"23.32.0.0/12",
			"23.64.0.0/14",
			"23.72.0.0/13",
			"104.64.0.0/10",
		},
		"Fastly": {
			"23.235.32.0/20",
			"151.101.0.0/16",
		},
		"Amazon CloudFront": {
			"13.32.0.0/15",
			"52.222.0.0/16",
			"54.182.0.0/16",
			"54.192.0.0/16",
			"54.230.0.0/16",
			"54.239.128.0/18",
		},
	}

	// 简单模拟，实际应该检查IP是否在CIDR范围内
	for cdn, ranges := range cdnRanges {
		for _, cidr := range ranges {
			// 简化判断，实际应该使用net.ParseCIDR和包含检查
			if strings.HasPrefix(ip, cidr[:strings.LastIndex(cidr, ".")]) {
				p.logger.Info("IP %s 可能属于 %s CDN", ip, cdn)
				return true
			}
		}
	}

	return false
}

// analyzeMailServers 分析邮件服务器
func (p *NetworkReconPlugin) analyzeMailServers(domain string, timeout int) ([]IPInfo, error) {
	var results []IPInfo

	// 查找MX记录
	mxRecords, err := net.LookupMX(domain)
	if err != nil {
		return nil, fmt.Errorf("MX记录查询失败: %v", err)
	}

	for _, mx := range mxRecords {
		// 解析邮件服务器IP
		ips, err := net.LookupIP(mx.Host)
		if err == nil {
			for _, ip := range ips {
				if ipv4 := ip.To4(); ipv4 != nil {
					// 检查是否是CDN IP
					if !p.isCDNIP(ipv4.String()) {
						results = append(results, IPInfo{
							Address:    ipv4.String(),
							Source:     "邮件服务器 - " + mx.Host,
							Confidence: 50,
						})
					}
				}
			}
		}
	}

	return results, nil
}

// checkCloudProviders 检查云服务提供商
func (p *NetworkReconPlugin) checkCloudProviders(domain string, timeout int) ([]IPInfo, error) {
	// 此功能在实际项目中需要实现，这里仅返回空结果
	return []IPInfo{}, nil
}

// getWebsiteFingerprint 获取网站指纹
func (p *NetworkReconPlugin) getWebsiteFingerprint(url string, timeout int) (string, error) {
	client := &http.Client{
		Timeout: time.Duration(timeout) * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}

	// 添加常见浏览器User-Agent
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

	resp, err := client.Do(req)
	if err != nil {
		// 尝试HTTP
		if strings.HasPrefix(url, "https://") {
			url = strings.Replace(url, "https://", "http://", 1)
			req, err = http.NewRequest("GET", url, nil)
			if err != nil {
				return "", err
			}
			req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
			resp, err = client.Do(req)
			if err != nil {
				return "", err
			}
		} else {
			return "", err
		}
	}
	defer resp.Body.Close()

	// 读取前10KB内容作为指纹
	maxSize := 10 * 1024
	body := make([]byte, maxSize)
	n, err := io.ReadAtLeast(resp.Body, body, maxSize)
	if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
		return "", err
	}

	// 提取HTTP头和HTML标题，构建指纹
	var fingerprint strings.Builder

	// 添加HTTP状态码
	fingerprint.WriteString(fmt.Sprintf("STATUS:%d;", resp.StatusCode))

	// 添加HTTP头
	for _, header := range []string{"Server", "X-Powered-By", "Content-Type"} {
		if value := resp.Header.Get(header); value != "" {
			fingerprint.WriteString(fmt.Sprintf("%s:%s;", header, value))
		}
	}

	// 提取HTML标题
	bodyStr := string(body[:n])
	titleRegex := regexp.MustCompile(`<title[^>]*>([^<]+)</title>`)
	if matches := titleRegex.FindStringSubmatch(bodyStr); len(matches) > 1 {
		fingerprint.WriteString(fmt.Sprintf("TITLE:%s;", matches[1]))
	}

	// 提取meta标签
	metaRegex := regexp.MustCompile(`<meta\s+name=["']([^"']+)["']\s+content=["']([^"']+)["']`)
	metaMatches := metaRegex.FindAllStringSubmatch(bodyStr, -1)
	for _, match := range metaMatches {
		if len(match) > 2 {
			fingerprint.WriteString(fmt.Sprintf("META-%s:%s;", match[1], match[2]))
		}
	}

	return fingerprint.String(), nil
}

// calculateSimilarity 计算两个指纹的相似度
func (p *NetworkReconPlugin) calculateSimilarity(fp1, fp2 string) float64 {
	// 将指纹分解为键值对
	parse := func(fp string) map[string]string {
		result := make(map[string]string)
		parts := strings.Split(fp, ";")
		for _, part := range parts {
			if part == "" {
				continue
			}
			kv := strings.SplitN(part, ":", 2)
			if len(kv) == 2 {
				result[kv[0]] = kv[1]
			}
		}
		return result
	}

	map1 := parse(fp1)
	map2 := parse(fp2)

	// 特殊处理某些字段
	totalFields := 0
	matchedFields := 0

	// 比对状态码
	if status1, ok1 := map1["STATUS"]; ok1 {
		if status2, ok2 := map2["STATUS"]; ok2 {
			totalFields++
			if status1 == status2 {
				matchedFields++
			}
		}
	}

	// 比对标题
	if title1, ok1 := map1["TITLE"]; ok1 {
		if title2, ok2 := map2["TITLE"]; ok2 {
			totalFields++
			if title1 == title2 {
				matchedFields++
			} else {
				// 计算标题相似度
				words1 := strings.Fields(title1)
				words2 := strings.Fields(title2)
				commonWords := 0
				for _, w1 := range words1 {
					for _, w2 := range words2 {
						if strings.EqualFold(w1, w2) {
							commonWords++
							break
						}
					}
				}
				if len(words1) > 0 && len(words2) > 0 {
					titleSimilarity := float64(commonWords) / float64(max(len(words1), len(words2)))
					if titleSimilarity > 0.5 {
						matchedFields += int(titleSimilarity * 0.8) // 部分匹配
					}
				}
			}
		}
	}

	// 比对其他字段
	for k, v1 := range map1 {
		if k == "STATUS" || k == "TITLE" {
			continue // 已经比较过
		}
		if v2, ok := map2[k]; ok {
			totalFields++
			if v1 == v2 {
				matchedFields++
			}
		}
	}

	if totalFields == 0 {
		return 0.0
	}
	return float64(matchedFields) / float64(totalFields)
}

// max 返回两个整数中的较大值
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// sortIPsByConfidence 按可信度排序IP
func (p *NetworkReconPlugin) sortIPsByConfidence(ips []IPInfo) {
	sort.Slice(ips, func(i, j int) bool {
		return ips[i].Confidence > ips[j].Confidence
	})
}
